<template>
  <div class="accident-management">
    <!-- 功能切换 -->
    <div class="function-tabs">
      <a-radio-group v-model:value="activeTab" button-style="solid" size="large">
        <a-radio-button value="list">事件列表</a-radio-button>
        <a-radio-button value="report">事件登记</a-radio-button>
        <a-radio-button value="analysis">数据分析</a-radio-button>
        <a-radio-button value="prevention">预防措施</a-radio-button>
      </a-radio-group>
    </div>

    <!-- 事件列表 -->
    <div v-if="activeTab === 'list'" class="list-section">
      <a-card title="意外死亡事件列表" class="events-card">
        <template #extra>
          <a-space>
            <a-input-search v-model:value="searchKeyword" placeholder="搜索姓名、地点或事件类型" style="width: 300px" @search="handleSearch" />
            <a-select v-model:value="typeFilter" placeholder="事件类型" style="width: 120px">
              <a-select-option value="all">全部类型</a-select-option>
              <a-select-option value="traffic">交通事故</a-select-option>
              <a-select-option value="drowning">溺水</a-select-option>
              <a-select-option value="fall">坠落</a-select-option>
              <a-select-option value="fire">火灾</a-select-option>
              <a-select-option value="poisoning">中毒</a-select-option>
              <a-select-option value="other">其他</a-select-option>
            </a-select>
            <a-button @click="refreshData">
              <ReloadOutlined />
              刷新
            </a-button>
            <a-button @click="exportData">
              <ExportOutlined />
              导出
            </a-button>
          </a-space>
        </template>

        <a-table
          :columns="eventColumns"
          :data-source="filteredEvents"
          :loading="loading"
          :pagination="pagination"
          row-key="id"
          class="events-table"
          :locale="{ emptyText: filteredEvents.length === 0 && !loading ? '暂无意外事件数据，请点击刷新按钮加载数据' : '暂无数据' }"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'victim'">
              <a-space>
                <a-avatar size="small">{{ record.victimName?.charAt(0) }}</a-avatar>
                <div>
                  <div>{{ record.victimName }}</div>
                  <div class="victim-info">{{ record.victimAge }}岁 · {{ record.victimGender === 'male' ? '男' : '女' }}</div>
                </div>
              </a-space>
            </template>

            <template v-else-if="column.key === 'event'">
              <div>
                <div class="event-type">
                  <a-tag :color="getEventTypeColor(record.eventType)">
                    {{ getEventTypeName(record.eventType) }}
                  </a-tag>
                </div>
                <div class="event-time">{{ formatDateTime(record.eventTime) }}</div>
                <div class="event-location">{{ record.location }}</div>
              </div>
            </template>

            <template v-else-if="column.key === 'severity'">
              <a-tag :color="getSeverityColor(record.severity)">
                {{ getSeverityText(record.severity) }}
              </a-tag>
            </template>

            <template v-else-if="column.key === 'status'">
              <a-badge :status="getStatusBadge(record.investigationStatus)" :text="getStatusText(record.investigationStatus)" />
            </template>

            <template v-else-if="column.key === 'actions'">
              <a-space>
                <a-button type="link" size="small" @click="viewDetail(record)">详情</a-button>
                <a-button type="link" size="small" @click="editEvent(record)">编辑</a-button>
                <a-button type="link" size="small" @click="generateReport(record)">报告</a-button>
              </a-space>
            </template>
          </template>
        </a-table>
      </a-card>
    </div>

    <!-- 事件登记 -->
    <div v-if="activeTab === 'report'" class="report-section">
      <a-row :gutter="[24, 24]">
        <a-col :xs="24" :lg="16">
          <a-card title="意外事件登记" class="register-card">
            <a-form :model="reportForm" :rules="reportRules" ref="reportFormRef" layout="vertical">
              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item label="受害者姓名" name="victimName">
                    <a-input v-model:value="reportForm.victimName" placeholder="请输入受害者姓名" />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label="年龄" name="victimAge">
                    <a-input-number v-model:value="reportForm.victimAge" :min="0" :max="150" style="width: 100%" />
                  </a-form-item>
                </a-col>
              </a-row>

              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item label="性别" name="victimGender">
                    <a-radio-group v-model:value="reportForm.victimGender">
                      <a-radio value="male">男</a-radio>
                      <a-radio value="female">女</a-radio>
                    </a-radio-group>
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label="事件类型" name="eventType">
                    <a-select v-model:value="reportForm.eventType" placeholder="选择事件类型">
                      <a-select-option value="traffic">交通事故</a-select-option>
                      <a-select-option value="drowning">溺水</a-select-option>
                      <a-select-option value="fall">坠落</a-select-option>
                      <a-select-option value="fire">火灾</a-select-option>
                      <a-select-option value="poisoning">中毒</a-select-option>
                      <a-select-option value="other">其他</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
              </a-row>

              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item label="事件时间" name="eventTime">
                    <a-date-picker v-model:value="reportForm.eventTime" show-time placeholder="选择事件发生时间" style="width: 100%" />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label="事件地点" name="location">
                    <a-input v-model:value="reportForm.location" placeholder="请输入事件发生地点" />
                  </a-form-item>
                </a-col>
              </a-row>

              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item label="严重程度" name="severity">
                    <a-select v-model:value="reportForm.severity" placeholder="选择严重程度">
                      <a-select-option value="low">轻微</a-select-option>
                      <a-select-option value="medium">一般</a-select-option>
                      <a-select-option value="high">严重</a-select-option>
                      <a-select-option value="critical">重大</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label="目击者数量" name="witnesses">
                    <a-input-number v-model:value="reportForm.witnesses" :min="0" :max="50" style="width: 100%" />
                  </a-form-item>
                </a-col>
              </a-row>

              <a-form-item label="事件详情" name="description">
                <a-textarea v-model:value="reportForm.description" placeholder="请详细描述事件经过" :rows="4" />
              </a-form-item>

              <a-form-item label="初步原因分析" name="causeAnalysis">
                <a-textarea v-model:value="reportForm.causeAnalysis" placeholder="请分析事件可能的原因" :rows="3" />
              </a-form-item>

              <a-form-item label="预防建议" name="preventionSuggestions">
                <a-textarea v-model:value="reportForm.preventionSuggestions" placeholder="请提出预防类似事件的建议" :rows="3" />
              </a-form-item>

              <a-form-item>
                <a-space>
                  <a-button type="primary" @click="submitReport" :loading="submitting">提交报告</a-button>
                  <a-button @click="saveAsDraft">保存草稿</a-button>
                  <a-button @click="resetForm">重置</a-button>
                </a-space>
              </a-form-item>
            </a-form>
          </a-card>
        </a-col>

        <a-col :xs="24" :lg="8">
          <a-card title="登记指南" class="guide-card">
            <div class="guide-content">
              <h4>登记要点</h4>
              <ul>
                <li>请确保受害者信息准确无误</li>
                <li>详细记录事件发生的时间和地点</li>
                <li>客观描述事件经过，避免主观判断</li>
                <li>重点关注事件的直接原因</li>
                <li>提出切实可行的预防建议</li>
              </ul>

              <h4>事件分类说明</h4>
              <div class="classification-list">
                <div class="classification-item"><strong>交通事故：</strong>涉及车辆、行人的道路交通意外</div>
                <div class="classification-item"><strong>溺水：</strong>在水中发生的意外死亡事件</div>
                <div class="classification-item"><strong>坠落：</strong>从高处跌落导致的意外</div>
                <div class="classification-item"><strong>火灾：</strong>火灾或爆炸引起的意外死亡</div>
                <div class="classification-item"><strong>中毒：</strong>化学物质或食物中毒事件</div>
              </div>
            </div>
          </a-card>
        </a-col>
      </a-row>
    </div>

    <!-- 数据分析 -->
    <div v-if="activeTab === 'analysis'" class="analysis-section">
      <a-row :gutter="[24, 24]">
        <!-- 统计概览 -->
        <a-col :xs="24">
          <a-card title="统计概览" class="stats-card">
            <template #extra>
              <a-button @click="initCharts" size="small"> 刷新图表 </a-button>
            </template>
            <a-row :gutter="16">
              <a-col :xs="24" :sm="12" :lg="6">
                <a-statistic title="总事件数" :value="totalEvents" />
              </a-col>
              <a-col :xs="24" :sm="12" :lg="6">
                <a-statistic title="本月新增" :value="monthlyEvents" />
              </a-col>
              <a-col :xs="24" :sm="12" :lg="6">
                <a-statistic title="调查中" :value="investigatingEvents" />
              </a-col>
              <a-col :xs="24" :sm="12" :lg="6">
                <a-statistic title="平均年龄" :value="averageAge" suffix="岁" />
              </a-col>
            </a-row>
          </a-card>
        </a-col>

        <!-- 事件类型分布 -->
        <a-col :xs="24" :lg="12">
          <a-card title="事件类型分布" class="chart-card">
            <div class="chart-container">
              <div ref="typeChart" style="width: 100%; height: 300px"></div>
            </div>
          </a-card>
        </a-col>

        <!-- 时间趋势 -->
        <a-col :xs="24" :lg="12">
          <a-card title="月度趋势" class="chart-card">
            <div class="chart-container">
              <div ref="trendChart" style="width: 100%; height: 300px"></div>
            </div>
          </a-card>
        </a-col>

        <!-- 年龄分布 -->
        <a-col :xs="24" :lg="12">
          <a-card title="受害者年龄分布" class="chart-card">
            <div class="chart-container">
              <div ref="ageChart" style="width: 100%; height: 300px"></div>
            </div>
          </a-card>
        </a-col>

        <!-- 地区分布 -->
        <a-col :xs="24" :lg="12">
          <a-card title="地区分布" class="chart-card">
            <div class="region-stats">
              <div v-for="region in regionStats" :key="region.name" class="region-item">
                <div class="region-name">{{ region.name }}</div>
                <div class="region-count">{{ region.count }}起</div>
                <a-progress :percent="region.percentage" :stroke-color="getRegionColor(region.level)" />
              </div>
            </div>
          </a-card>
        </a-col>
      </a-row>
    </div>

    <!-- 预防措施 -->
    <div v-if="activeTab === 'prevention'" class="prevention-section">
      <a-row :gutter="[24, 24]">
        <a-col :xs="24" :lg="16">
          <a-card title="预防措施库" class="measures-card">
            <div class="measures-list">
              <div v-for="measure in preventionMeasures" :key="measure.id" class="measure-item">
                <div class="measure-header">
                  <h4>{{ measure.title }}</h4>
                  <a-tag :color="getEventTypeColor(measure.eventType)">
                    {{ getEventTypeName(measure.eventType) }}
                  </a-tag>
                </div>
                <div class="measure-content">
                  <p>{{ measure.description }}</p>
                  <div class="measure-steps">
                    <h5>具体措施：</h5>
                    <ul>
                      <li v-for="step in measure.steps" :key="step">{{ step }}</li>
                    </ul>
                  </div>
                  <div class="measure-effectiveness">
                    <span>预防效果评级：</span>
                    <a-rate :value="measure.effectiveness" disabled />
                  </div>
                </div>
              </div>
            </div>
          </a-card>
        </a-col>

        <a-col :xs="24" :lg="8">
          <a-card title="风险评估" class="risk-card">
            <div class="risk-assessment">
              <div class="risk-item">
                <div class="risk-type">交通安全风险</div>
                <div class="risk-level high">高风险</div>
                <div class="risk-desc">道路交通事故频发，需加强交通安全教育</div>
              </div>
              <div class="risk-item">
                <div class="risk-type">溺水风险</div>
                <div class="risk-level medium">中等风险</div>
                <div class="risk-desc">夏季溺水事件增多，需加强水域安全管理</div>
              </div>
              <div class="risk-item">
                <div class="risk-type">坠落风险</div>
                <div class="risk-level low">低风险</div>
                <div class="risk-desc">高空作业安全措施较好，风险可控</div>
              </div>
            </div>
          </a-card>

          <a-card title="安全提醒" class="reminder-card" style="margin-top: 24px">
            <div class="reminder-list">
              <div class="reminder-item">
                <ExclamationCircleOutlined style="color: #faad14" />
                <span>雨季来临，注意防范溺水事故</span>
              </div>
              <div class="reminder-item">
                <WarningOutlined style="color: #f5222d" />
                <span>节假日期间交通事故高发</span>
              </div>
              <div class="reminder-item">
                <InfoCircleOutlined style="color: #1890ff" />
                <span>定期检查消防设施完好性</span>
              </div>
            </div>
          </a-card>
        </a-col>
      </a-row>
    </div>

    <!-- 详情对话框 -->
    <a-modal v-model:open="showDetailModal" title="事件详情" width="800px" :footer="null">
      <div v-if="selectedEvent" class="detail-content">
        <a-descriptions title="基本信息" bordered :column="2">
          <a-descriptions-item label="受害者">{{ selectedEvent.victimName }}</a-descriptions-item>
          <a-descriptions-item label="年龄性别">{{ selectedEvent.victimAge }}岁 · {{ selectedEvent.victimGender === 'male' ? '男' : '女' }}</a-descriptions-item>
          <a-descriptions-item label="事件类型">{{ getEventTypeName(selectedEvent.eventType) }}</a-descriptions-item>
          <a-descriptions-item label="严重程度">{{ getSeverityText(selectedEvent.severity) }}</a-descriptions-item>
          <a-descriptions-item label="发生时间">{{ formatDateTime(selectedEvent.eventTime) }}</a-descriptions-item>
          <a-descriptions-item label="发生地点">{{ selectedEvent.location }}</a-descriptions-item>
          <a-descriptions-item label="目击者">{{ selectedEvent.witnesses }}人</a-descriptions-item>
          <a-descriptions-item label="调查状态">{{ getStatusText(selectedEvent.investigationStatus) }}</a-descriptions-item>
          <a-descriptions-item label="事件描述" :span="2">{{ selectedEvent.description }}</a-descriptions-item>
          <a-descriptions-item label="原因分析" :span="2">{{ selectedEvent.causeAnalysis }}</a-descriptions-item>
          <a-descriptions-item label="预防建议" :span="2">{{ selectedEvent.preventionSuggestions }}</a-descriptions-item>
        </a-descriptions>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import * as echarts from 'echarts'
import { ExportOutlined, ReloadOutlined, ExclamationCircleOutlined, WarningOutlined, InfoCircleOutlined } from '@ant-design/icons-vue'
import { useLifeDeathStore } from '@/stores/lifeDeath'

// Store
const lifeDeathStore = useLifeDeathStore()

// 响应式数据
const activeTab = ref('list')
const searchKeyword = ref('')
const typeFilter = ref('all')
const showDetailModal = ref(false)
const selectedEvent = ref(null)
const submitting = ref(false)

// Chart refs
const typeChart = ref(null)
const trendChart = ref(null)
const ageChart = ref(null)

// Form refs
const reportFormRef = ref()

// 登记表单
const reportForm = ref({
  victimName: '',
  victimAge: null,
  victimGender: 'male',
  eventType: '',
  eventTime: null,
  location: '',
  severity: '',
  witnesses: 0,
  description: '',
  causeAnalysis: '',
  preventionSuggestions: ''
})

const reportRules = {
  victimName: [{ required: true, message: '请输入受害者姓名' }],
  victimAge: [{ required: true, message: '请输入年龄' }],
  eventType: [{ required: true, message: '请选择事件类型' }],
  eventTime: [{ required: true, message: '请选择事件时间' }],
  location: [{ required: true, message: '请输入事件地点' }],
  severity: [{ required: true, message: '请选择严重程度' }],
  description: [{ required: true, message: '请描述事件经过' }]
}

// 表格列定义
const eventColumns = [
  { title: '受害者', key: 'victim', width: 150 },
  { title: '事件信息', key: 'event', width: 200 },
  { title: '严重程度', key: 'severity', width: 100 },
  { title: '调查状态', key: 'status', width: 120 },
  { title: '登记时间', dataIndex: 'createdAt', key: 'createdAt', width: 120, customRender: ({ text }) => formatDateTime(text) },
  { title: '操作', key: 'actions', width: 180, fixed: 'right' }
]

const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true
})

// 计算属性
const loading = computed(() => lifeDeathStore.loading)

const filteredEvents = computed(() => {
  let events = lifeDeathStore.specialCases.filter((c) => c.caseType === 'accident')

  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    events = events.filter((event) => event.victimName?.toLowerCase().includes(keyword) || event.location?.toLowerCase().includes(keyword) || event.eventType?.toLowerCase().includes(keyword))
  }

  if (typeFilter.value !== 'all') {
    events = events.filter((event) => event.eventType === typeFilter.value)
  }

  pagination.value.total = events.length
  return events
})

const totalEvents = computed(() => lifeDeathStore.specialCases.filter((c) => c.caseType === 'accident').length)

const monthlyEvents = computed(() => {
  const thisMonth = dayjs().format('YYYY-MM')
  return lifeDeathStore.specialCases.filter((c) => c.caseType === 'accident' && dayjs(c.createdAt).format('YYYY-MM') === thisMonth).length
})

const investigatingEvents = computed(() => lifeDeathStore.specialCases.filter((c) => c.caseType === 'accident' && c.investigationStatus === 'investigating').length)

const averageAge = computed(() => {
  const events = lifeDeathStore.specialCases.filter((c) => c.caseType === 'accident')
  if (events.length === 0) return 0

  const totalAge = events.reduce((sum, event) => sum + (event.victimAge || 0), 0)
  return Math.round(totalAge / events.length)
})

const regionStats = computed(() => {
  const regions = ['城区', '郊区', '乡村', '山区', '水域']
  const total = lifeDeathStore.specialCases.filter((c) => c.caseType === 'accident').length

  return regions.map((region) => {
    const count = Math.floor(Math.random() * 20) + 1
    const percentage = total > 0 ? Math.round((count / total) * 100) : 0
    const level = percentage > 30 ? 'high' : percentage > 15 ? 'medium' : 'low'

    return { name: region, count, percentage, level }
  })
})

const preventionMeasures = ref([
  {
    id: 1,
    title: '交通安全防护措施',
    eventType: 'traffic',
    description: '针对道路交通事故的综合防护措施',
    steps: ['加强交通安全教育和宣传', '完善道路标志和信号设施', '严格执行交通法规', '提高驾驶员安全意识', '改善道路交通环境'],
    effectiveness: 4
  },
  {
    id: 2,
    title: '溺水预防措施',
    eventType: 'drowning',
    description: '水域安全管理和溺水预防措施',
    steps: ['在危险水域设置警示标志', '配备专业救生设备', '加强游泳安全教育', '建立水域巡查制度', '提供急救培训'],
    effectiveness: 4
  },
  {
    id: 3,
    title: '高空坠落防护',
    eventType: 'fall',
    description: '高空作业和建筑安全防护措施',
    steps: ['规范高空作业操作流程', '配备专业防护设备', '定期检查安全设施', '加强作业人员培训', '建立安全检查制度'],
    effectiveness: 5
  }
])

// 方法
const handleSearch = () => {
  // 搜索逻辑已在computed中处理
}

const viewDetail = (event) => {
  selectedEvent.value = event
  showDetailModal.value = true
}

const editEvent = (event) => {
  message.info('编辑功能开发中...')
}

const generateReport = (event) => {
  message.success(`正在生成 ${event.victimName} 事件报告`)
}

const exportData = () => {
  message.success('数据导出功能开发中...')
}

const refreshData = async () => {
  try {
    await lifeDeathStore.fetchLifeRecords()
    message.success('数据刷新完成')
    console.log(
      '刷新后的意外事件数据:',
      lifeDeathStore.specialCases.filter((c) => c.caseType === 'accident')
    )
  } catch (error) {
    message.error('数据刷新失败')
    console.error('刷新数据时出错:', error)
  }
}

const submitReport = async () => {
  try {
    await reportFormRef.value.validate()
    submitting.value = true

    const eventData = {
      ...reportForm.value,
      eventTime: reportForm.value.eventTime.toISOString(),
      caseType: 'accident',
      investigationStatus: 'investigating',
      createdAt: new Date().toISOString()
    }

    // 这里应该调用store方法保存数据
    // await lifeDeathStore.addSpecialCase(eventData)

    message.success('事件报告提交成功')
    resetForm()
  } catch (error) {
    // 验证失败
  } finally {
    submitting.value = false
  }
}

const saveAsDraft = () => {
  message.success('草稿已保存')
}

const resetForm = () => {
  reportFormRef.value?.resetFields()
}

// 绘制图表
const drawTypeChart = () => {
  console.log('开始绘制事件类型分布图')

  if (!typeChart.value) {
    console.log('TypeChart 容器不存在')
    return
  }

  // 销毁已存在的图表实例
  echarts.dispose(typeChart.value)

  try {
    // 从store获取实际数据，如果没有数据则使用模拟数据
    const accidentEvents = lifeDeathStore.specialCases.filter((c) => c.caseType === 'accident')

    const types = {
      交通事故: accidentEvents.filter((e) => e.eventType === 'traffic').length || 15,
      溺水: accidentEvents.filter((e) => e.eventType === 'drowning').length || 8,
      坠落: accidentEvents.filter((e) => e.eventType === 'fall').length || 5,
      火灾: accidentEvents.filter((e) => e.eventType === 'fire').length || 3,
      中毒: accidentEvents.filter((e) => e.eventType === 'poisoning').length || 2,
      其他: accidentEvents.filter((e) => e.eventType === 'other').length || 4
    }

    console.log('事件类型数据:', types)

    // 转换为ECharts需要的数据格式
    const chartData = Object.entries(types).map(([name, value]) => ({
      name,
      value
    }))

    // 初始化ECharts实例 - 移除dark主题，使用默认主题
    const chart = echarts.init(typeChart.value)

    // 配置图表选项 - 简化配置以确保基本显示
    const option = {
      title: {
        text: '事件类型分布',
        left: 'center',
        textStyle: {
          color: '#fff',
          fontSize: 16
        }
      },
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c} ({d}%)'
      },
      legend: {
        type: 'scroll',
        orient: 'horizontal',
        bottom: 10,
        textStyle: {
          color: '#fff'
        }
      },
      series: [
        {
          name: '事件类型',
          type: 'pie',
          radius: ['30%', '70%'],
          center: ['50%', '50%'],
          data: chartData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          },
          label: {
            show: true,
            color: '#fff'
          },
          labelLine: {
            lineStyle: {
              color: '#fff'
            }
          }
        }
      ]
    }

    // 设置图表选项
    chart.setOption(option)

    // 响应式调整
    const resizeHandler = () => {
      chart.resize()
    }
    window.addEventListener('resize', resizeHandler)

    console.log('事件类型分布图绘制完成')
  } catch (error) {
    console.error('绘制事件类型分布图时出错:', error)
  }
}

const drawTrendChart = () => {
  console.log('开始绘制月度趋势图')

  if (!trendChart.value) {
    console.log('TrendChart 容器不存在')
    return
  }

  // 销毁已存在的图表实例
  echarts.dispose(trendChart.value)

  try {
    // 获取最近12个月的数据
    const monthlyData = []
    const monthLabels = []

    for (let i = 11; i >= 0; i--) {
      const month = dayjs().subtract(i, 'month')
      monthLabels.push(month.format('MM月'))

      // 从store获取该月的意外事件数量
      const monthStr = month.format('YYYY-MM')
      const monthEvents = lifeDeathStore.specialCases.filter((c) => c.caseType === 'accident' && dayjs(c.createdAt).format('YYYY-MM') === monthStr).length

      const eventCount = monthEvents > 0 ? monthEvents : Math.floor(Math.random() * 15) + 2
      monthlyData.push(eventCount)
    }

    console.log('月度趋势数据:', monthlyData)

    // 初始化ECharts实例 - 移除dark主题，使用默认主题
    const chart = echarts.init(trendChart.value)

    // 配置图表选项 - 简化配置
    const option = {
      title: {
        text: '月度趋势',
        left: 'center',
        textStyle: {
          color: '#fff',
          fontSize: 16
        }
      },
      tooltip: {
        trigger: 'axis',
        formatter: function (params) {
          const item = params[0]
          return `${item.name}<br/>意外事件: ${item.value}件`
        }
      },
      grid: {
        left: '10%',
        right: '10%',
        bottom: '15%',
        top: '20%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: monthLabels,
        axisLine: {
          lineStyle: {
            color: '#fff'
          }
        },
        axisLabel: {
          color: '#fff'
        }
      },
      yAxis: {
        type: 'value',
        name: '事件数量',
        nameTextStyle: {
          color: '#fff'
        },
        axisLine: {
          lineStyle: {
            color: '#fff'
          }
        },
        axisLabel: {
          color: '#fff'
        },
        splitLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.2)'
          }
        }
      },
      series: [
        {
          name: '意外事件',
          type: 'line',
          data: monthlyData,
          smooth: true,
          lineStyle: {
            color: '#40a9ff',
            width: 2
          },
          itemStyle: {
            color: '#40a9ff'
          },
          areaStyle: {
            color: 'rgba(64, 169, 255, 0.3)'
          }
        }
      ]
    }

    // 设置图表选项
    chart.setOption(option)

    // 响应式调整
    const resizeHandler = () => {
      chart.resize()
    }
    window.addEventListener('resize', resizeHandler)

    console.log('月度趋势图绘制完成')
  } catch (error) {
    console.error('绘制月度趋势图时出错:', error)
  }
}

const drawAgeChart = () => {
  console.log('开始绘制年龄分布图')

  if (!ageChart.value) {
    console.log('AgeChart 容器不存在')
    return
  }

  // 销毁已存在的图表实例
  echarts.dispose(ageChart.value)

  try {
    // 从store获取实际数据，如果没有数据则使用模拟数据
    const accidentVictims = lifeDeathStore.specialCases.filter((c) => c.caseType === 'accident')

    const ageGroups = ['0-18', '19-35', '36-50', '51-65', '65+']
    const data = [
      accidentVictims.filter((v) => v.victimAge <= 18).length || 3,
      accidentVictims.filter((v) => v.victimAge > 18 && v.victimAge <= 35).length || 12,
      accidentVictims.filter((v) => v.victimAge > 35 && v.victimAge <= 50).length || 8,
      accidentVictims.filter((v) => v.victimAge > 50 && v.victimAge <= 65).length || 6,
      accidentVictims.filter((v) => v.victimAge > 65).length || 4
    ]

    console.log('年龄分布数据:', data)

    // 初始化ECharts实例 - 移除dark主题，使用默认主题
    const chart = echarts.init(ageChart.value)

    // 配置图表选项 - 简化配置
    const option = {
      title: {
        text: '受害者年龄分布',
        left: 'center',
        textStyle: {
          color: '#fff',
          fontSize: 16
        }
      },
      tooltip: {
        trigger: 'axis',
        formatter: function (params) {
          const item = params[0]
          return `年龄段: ${item.name}<br/>人数: ${item.value}人`
        }
      },
      grid: {
        left: '10%',
        right: '10%',
        bottom: '15%',
        top: '20%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: ageGroups,
        axisLine: {
          lineStyle: {
            color: '#fff'
          }
        },
        axisLabel: {
          color: '#fff'
        }
      },
      yAxis: {
        type: 'value',
        name: '人数',
        nameTextStyle: {
          color: '#fff'
        },
        axisLine: {
          lineStyle: {
            color: '#fff'
          }
        },
        axisLabel: {
          color: '#fff'
        },
        splitLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.2)'
          }
        }
      },
      series: [
        {
          name: '受害者人数',
          type: 'bar',
          data: data,
          itemStyle: {
            color: '#52c41a',
            borderRadius: [4, 4, 0, 0]
          },
          label: {
            show: true,
            position: 'top',
            color: '#fff'
          }
        }
      ]
    }

    // 设置图表选项
    chart.setOption(option)

    // 响应式调整
    const resizeHandler = () => {
      chart.resize()
    }
    window.addEventListener('resize', resizeHandler)

    console.log('年龄分布图绘制完成')
  } catch (error) {
    console.error('绘制年龄分布图时出错:', error)
  }
}

// 工具方法
const getEventTypeColor = (type) => {
  const colors = {
    traffic: 'red',
    drowning: 'blue',
    fall: 'orange',
    fire: 'volcano',
    poisoning: 'purple',
    other: 'default'
  }
  return colors[type] || 'default'
}

const getEventTypeName = (type) => {
  const names = {
    traffic: '交通事故',
    drowning: '溺水',
    fall: '坠落',
    fire: '火灾',
    poisoning: '中毒',
    other: '其他'
  }
  return names[type] || type
}

const getSeverityColor = (severity) => {
  const colors = {
    low: 'green',
    medium: 'orange',
    high: 'red',
    critical: 'volcano'
  }
  return colors[severity] || 'default'
}

const getSeverityText = (severity) => {
  const texts = {
    low: '轻微',
    medium: '一般',
    high: '严重',
    critical: '重大'
  }
  return texts[severity] || severity
}

const getStatusBadge = (status) => {
  const badges = {
    investigating: 'processing',
    completed: 'success',
    pending: 'warning',
    closed: 'default'
  }
  return badges[status] || 'default'
}

const getStatusText = (status) => {
  const texts = {
    investigating: '调查中',
    completed: '已完成',
    pending: '待处理',
    closed: '已关闭'
  }
  return texts[status] || status
}

const getRegionColor = (level) => {
  const colors = {
    high: '#f5222d',
    medium: '#faad14',
    low: '#52c41a'
  }
  return colors[level] || '#d9d9d9'
}

const formatDateTime = (dateTime) => {
  return dayjs(dateTime).format('YYYY-MM-DD HH:mm')
}

// 生命周期
onMounted(async () => {
  // 确保数据已加载
  await lifeDeathStore.fetchLifeRecords()

  // 延迟初始化图表，确保DOM完全渲染
  setTimeout(() => {
    console.log('开始初始化所有图表')
    console.log(
      '意外事件数据:',
      lifeDeathStore.specialCases.filter((c) => c.caseType === 'accident')
    )
    if (activeTab.value === 'analysis') {
      initCharts()
    }
  }, 100)
})

// 监听标签页切换
watch(activeTab, (newTab) => {
  if (newTab === 'analysis') {
    // 切换到分析页面时初始化图表
    nextTick(() => {
      setTimeout(() => {
        initCharts()
      }, 100)
    })
  }
})

// 初始化所有图表
const initCharts = () => {
  console.log('初始化图表中...')
  console.log('图表容器状态:')
  console.log('typeChart.value:', typeChart.value)
  console.log('trendChart.value:', trendChart.value)
  console.log('ageChart.value:', ageChart.value)

  drawTypeChart()
  drawTrendChart()
  drawAgeChart()

  message.success('图表刷新完成')
}

// 组件销毁时清理图表实例
onUnmounted(() => {
  try {
    if (typeChart.value) {
      echarts.dispose(typeChart.value)
    }
    if (trendChart.value) {
      echarts.dispose(trendChart.value)
    }
    if (ageChart.value) {
      echarts.dispose(ageChart.value)
    }
  } catch (error) {
    console.error('清理图表实例时出错:', error)
  }
})
</script>

<style lang="scss" scoped>
@use '@/styles/variables.scss' as *;

.accident-management {
  .function-tabs {
    margin-bottom: 24px;
    text-align: center;
  }

  .events-table {
    .victim-info {
      font-size: 12px;
      color: $text-tertiary;
    }

    .event-type {
      margin-bottom: 4px;
    }

    .event-time,
    .event-location {
      font-size: 12px;
      color: $text-secondary;
      margin-bottom: 2px;
    }
  }

  .guide-content {
    h4 {
      color: $text-primary;
      margin-bottom: 12px;
    }

    ul {
      margin-bottom: 20px;
      padding-left: 20px;
      color: $text-secondary;

      li {
        margin-bottom: 8px;
      }
    }

    .classification-list {
      .classification-item {
        margin-bottom: 12px;
        padding: 8px;
        background: rgba(255, 255, 255, 0.05);
        border-radius: 4px;
        font-size: 12px;
        color: $text-secondary;

        strong {
          color: $text-primary;
        }
      }
    }
  }

  .chart-container {
    width: 100%;
    height: 300px;
    min-height: 300px;
    display: flex;
    justify-content: center;
    align-items: center;

    > div {
      width: 100% !important;
      height: 100% !important;
    }
  }

  .region-stats {
    .region-item {
      margin-bottom: 16px;

      .region-name {
        font-weight: 500;
        color: $text-primary;
        margin-bottom: 4px;
      }

      .region-count {
        font-size: 12px;
        color: $text-secondary;
        margin-bottom: 8px;
      }
    }
  }

  .measures-list {
    .measure-item {
      margin-bottom: 24px;
      padding: 16px;
      background: rgba(255, 255, 255, 0.05);
      border: 1px solid $border-color;
      border-radius: 8px;

      .measure-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12px;

        h4 {
          color: $text-primary;
          margin: 0;
        }
      }

      .measure-content {
        p {
          color: $text-secondary;
          margin-bottom: 12px;
        }

        .measure-steps {
          margin-bottom: 12px;

          h5 {
            color: $text-primary;
            margin-bottom: 8px;
          }

          ul {
            padding-left: 20px;
            color: $text-secondary;

            li {
              margin-bottom: 4px;
            }
          }
        }

        .measure-effectiveness {
          display: flex;
          align-items: center;
          gap: 8px;
          color: $text-secondary;
        }
      }
    }
  }

  .risk-assessment {
    .risk-item {
      margin-bottom: 16px;
      padding: 12px;
      background: rgba(255, 255, 255, 0.05);
      border-radius: 8px;

      .risk-type {
        font-weight: 500;
        color: $text-primary;
        margin-bottom: 4px;
      }

      .risk-level {
        font-size: 12px;
        margin-bottom: 8px;

        &.high {
          color: #f5222d;
        }
        &.medium {
          color: #faad14;
        }
        &.low {
          color: #52c41a;
        }
      }

      .risk-desc {
        font-size: 12px;
        color: $text-secondary;
      }
    }
  }

  .reminder-list {
    .reminder-item {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-bottom: 12px;
      color: $text-secondary;
      font-size: 12px;
    }
  }

  .detail-content {
    color: $text-primary;
  }
}
</style>
